package com.mengtian_tech.smart_lab.controller.console.register;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.PasswordUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import com.mengtian_tech.smart_lab.entity.register.RegisterInfoEntity;
import com.mengtian_tech.smart_lab.entity.system.TSBaseUser;
import com.mengtian_tech.smart_lab.entity.system.TSRole;
import com.mengtian_tech.smart_lab.entity.system.TSRoleUser;
import com.mengtian_tech.smart_lab.entity.system.TSUser;
import com.mengtian_tech.smart_lab.entity.user.UserType;
import com.mengtian_tech.smart_lab.service.register.RegisterInfoServiceI;

/**   
 * @Title: Controller
 * @Description: 注册信息
 * @author onlineGenerator
 * @date 2016-06-09 17:09:00
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/registerInfoController")
public class RegisterInfoController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RegisterInfoController.class);

	@Autowired
	private RegisterInfoServiceI registerInfoService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 注册信息列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/mengtian_tech/smart_lab/register/registerInfoList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(RegisterInfoEntity registerInfo,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
 		CriteriaQuery cq = new CriteriaQuery(RegisterInfoEntity.class, dataGrid);
		//查询条件组装器 
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, registerInfo, request.getParameterMap());
		try{
		//自定义追加查询条件
			cq.eq("audit", false);
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.registerInfoService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除注册信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(RegisterInfoEntity registerInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		registerInfo = systemService.getEntity(RegisterInfoEntity.class, registerInfo.getId());
		message = "注册信息删除成功";
		try{
			registerInfoService.delete(registerInfo);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "注册信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除注册信息
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "注册信息删除成功";
		try{
			for(String id:ids.split(",")){
				RegisterInfoEntity registerInfo = systemService.getEntity(RegisterInfoEntity.class, 
				id
				);
				registerInfoService.delete(registerInfo);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "注册信息删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加注册信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(RegisterInfoEntity registerInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "注册信息提交成功！";
		try{
			
			//校验用户存在
			String userId = registerInfo.getUserId();
			List<TSBaseUser> list = systemService.findByProperty(TSBaseUser.class, "userName", userId);
			if(list.size() > 0){
				j.setSuccess(false);
				j.setMsg("用户名已存在！");
				return j;
			}
			
			registerInfo.setAudit(true);
			registerInfo.setCreateDate(new Date());
			String registerId = (String) registerInfoService.save(registerInfo);
			
			//自动审核通过
			TSUser users =  new TSUser();
 			users.setMobilePhone(registerInfo.getCellphone());
 			users.setRealName(registerInfo.getName());
			users.setStatus(Globals.User_Normal);
			users.setUserName(registerInfo.getUserId());
			users.setPassword(PasswordUtil.encrypt(registerId, registerInfo.getPasswd(), PasswordUtil.getStaticSalt()));
			users.setEmail(registerInfo.getEmail());			
			users.setUserType(UserType.temp);
			String id = (String) systemService.save(users);
			users.setId(id);			
			String roleid = TSRole.ROLE_TEMP_USER_ID; 
			saveRoleUser(users, roleid); 			
			
		}catch(Exception e){
			e.printStackTrace();
			message = "注册信息添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新注册信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(RegisterInfoEntity registerInfo, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "注册信息更新成功";
		RegisterInfoEntity t = registerInfoService.get(RegisterInfoEntity.class, registerInfo.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(registerInfo, t);
			registerInfoService.saveOrUpdate(t);
		} catch (Exception e) {
			e.printStackTrace();
			message = "注册信息更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 注册信息新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(RegisterInfoEntity registerInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(registerInfo.getId())) {
			registerInfo = registerInfoService.getEntity(RegisterInfoEntity.class, registerInfo.getId());
			req.setAttribute("registerInfoPage", registerInfo);
		}else{
			registerInfo.setSex("0");
			req.setAttribute("registerInfoPage", registerInfo);
		}
		
		return new ModelAndView("com/mengtian_tech/smart_lab/register/registerInfo-add");
	}
	/**
	 * 注册信息编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(RegisterInfoEntity registerInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(registerInfo.getId())) {
			registerInfo = registerInfoService.getEntity(RegisterInfoEntity.class, registerInfo.getId());
			req.setAttribute("registerInfoPage", registerInfo);
		}
		return new ModelAndView("com/mengtian_tech/smart_lab/register/registerInfo-update");
	}
	
	/**
	 * 显示审核页面
	 * @param registerInfo
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "goAudit")
	public ModelAndView goAudit(RegisterInfoEntity registerInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(registerInfo.getId())) {
			registerInfo = registerInfoService.getEntity(RegisterInfoEntity.class, registerInfo.getId());
			req.setAttribute("registerInfoPage", registerInfo);
		}
		return new ModelAndView("com/mengtian_tech/smart_lab/register/registerAudit");
	} 
 
	
	@RequestMapping(params = "audit")
	@ResponseBody
	public AjaxJson audit(RegisterInfoEntity registerInfo, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(registerInfo.getId())) {
			registerInfo = registerInfoService.getEntity(RegisterInfoEntity.class, registerInfo.getId());
			registerInfo.setAudit(true);
			registerInfoService.save(registerInfo);
			
			//创建系统用户
			TSUser users =  new TSUser();
 			users.setMobilePhone(registerInfo.getCellphone());
 			users.setRealName(registerInfo.getName());
			users.setStatus(Globals.User_Normal);
			users.setUserName(registerInfo.getUserId());
			users.setPassword(PasswordUtil.encrypt(registerInfo.getUserId(), "123456", PasswordUtil.getStaticSalt()));
			String id = (String) systemService.save(users);
			users.setId(id);
			users.setEmail(registerInfo.getEmail());
			
			String roleid = oConvertUtils.getString(req.getParameter("roleid")); 
			saveRoleUser(users, roleid); 
			
			AjaxJson json = new AjaxJson();
			json.setSuccess(true);
			json.setMsg("审核成功！");
			return json;
		}
		return null;
	}
	
	 protected void saveRoleUser(TSUser user, String roleidstr) {
			String[] roleids = roleidstr.split(",");
			for (int i = 0; i < roleids.length; i++) {
				TSRoleUser rUser = new TSRoleUser();
				TSRole role = systemService.getEntity(TSRole.class, roleids[i]);
				rUser.setTSRole(role);
				rUser.setTSUser(user);
				systemService.save(rUser); 
			}  
	 }
	    
	 
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","registerInfoController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(RegisterInfoEntity registerInfo,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(RegisterInfoEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, registerInfo, request.getParameterMap());
		List<RegisterInfoEntity> registerInfos = this.registerInfoService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"注册信息");
		modelMap.put(NormalExcelConstants.CLASS,RegisterInfoEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("注册信息列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,registerInfos);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(RegisterInfoEntity registerInfo,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"注册信息");
    	modelMap.put(NormalExcelConstants.CLASS,RegisterInfoEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("注册信息列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	 
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<RegisterInfoEntity> list() {
		List<RegisterInfoEntity> listRegisterInfos=registerInfoService.getList(RegisterInfoEntity.class);
		return listRegisterInfos;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		RegisterInfoEntity task = registerInfoService.get(RegisterInfoEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody RegisterInfoEntity registerInfo, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<RegisterInfoEntity>> failures = validator.validate(registerInfo);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		registerInfoService.save(registerInfo);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = registerInfo.getId();
		URI uri = uriBuilder.path("/rest/registerInfoController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(params="existUsername")
	@ResponseBody
	public AjaxJson isUserNameExist(String name,HttpServletRequest req){
		AjaxJson json = new AjaxJson();
		
		List list = registerInfoService.findByProperty(RegisterInfoEntity.class, "userId", name);
		List list2  = registerInfoService.findByProperty(TSBaseUser.class, "userName", name);
	 
		if(list.size() > 0 || list2.size() > 0) {
			json.setSuccess(true);
		} else{
			json.setSuccess(false);
		}
		
		return json;
	}
}
